package com.hc.core.web.springmvc.suppot;



import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestParameterPropertyValues;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


/**
 * 自定义数据绑定类。主要为了给传来的参数增加通用的前缀。<br>
 * 
 * @see ServletRequestDataBinder
 * @see BaseController
 * 
 */
public class MyRequestDataBinder extends WebDataBinder {

	private String prefix; //参数前缀

	private String prefixSeparator; //参数前缀与参数之间的分隔符

	public MyRequestDataBinder(Object target) {
		super(target);
	}

	public MyRequestDataBinder(Object target, String objectName) {
		super(target, objectName);
	}

	public void bind(ServletRequest request) {
		MutablePropertyValues mpvs = new ServletRequestParameterPropertyValues(request, getPrefix(),
				getPrefixSeparator());
		if (request instanceof MultipartHttpServletRequest) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			if (getPrefix() == null) {
				bindMultipartFiles(multipartRequest.getFileMap(), mpvs);
			} else {
				bindMultipartFiles(multipartRequest.getFileMap(), mpvs, getPrefix() + getPrefixSeparator());
			}

		}
		doBind(mpvs);
	}

	/**
	 * 绑定上传文件参数。有前缀
	 * 
	 * @param multipartFiles
	 * @param mpvs
	 * @param prefix
	 */
	protected void bindMultipartFiles(Map multipartFiles, MutablePropertyValues mpvs, String prefix) {
		for (Iterator it = multipartFiles.entrySet().iterator(); it.hasNext();) {
			Map.Entry entry = (Map.Entry) it.next();
			String key = (String) entry.getKey();
			if (key.startsWith(prefix)) {
				MultipartFile value = (MultipartFile) entry.getValue();
				if (isBindEmptyMultipartFiles() || !value.isEmpty()) {
					mpvs.addPropertyValue(key.substring(prefix.length()), value);
				}
			} else {

			}
		}
	}

	public void closeNoCatch() throws ServletRequestBindingException {
		if (getBindingResult().hasErrors()) {
			throw new ServletRequestBindingException("Errors binding onto object '"
					+ getBindingResult().getObjectName() + "'", new BindException(getBindingResult()));
		}
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public String getPrefixSeparator() {
		return prefixSeparator;
	}

	public void setPrefixSeparator(String prefixSeparator) {
		this.prefixSeparator = prefixSeparator;
	}

}
